﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Data.Common;
using Data.Enum;
using Data.Model;
using Data.ViewModel;
using DataAccess.SystemManage;
using Ninject;
using WinForm.Common;
using WinForm.Dialog;
using WinForm.Helper;
using WinForm.Properties;

namespace WinForm.SystemManage
{
    public partial class FrmPrivilegeManage : Form
    {
        private static readonly IKernel Kernel = new StandardKernel(new DbModule());
        private readonly ISysUser _sysUser = Kernel.Get<ISysUser>();
        private readonly ISysRole _sysRole = Kernel.Get<ISysRole>();
        private readonly ISysPrivilege _sysPrivilege = Kernel.Get<ISysPrivilege>();

        public FrmPrivilegeManage()
        {
            InitializeComponent();
        }

        private void FrmPrivilegeManage_Load(object sender, EventArgs e)
        {
            //分页控件初始化
            xpbUser.PageIndex = 1;
            xpbUser.PageSize = 20;
            xpbUser.xRefresh += RefreshUserManage;

            xpbRole.PageIndex = 1;
            xpbRole.PageSize = 20;
            xpbRole.xRefresh += RefreshRoleManage;

            xpbPrivilege.PageIndex = 1;
            xpbPrivilege.PageSize = 20;
            xpbPrivilege.xRefresh += RefreshPrivilegeManage;

            InitialCmbBox();
        }

        private void InitialCmbBox()
        {
            string errorMessage = string.Empty;
            try
            {
                ResultInfo<PagingDataSet<Role>> roles= _sysRole.GetRoles(1, int.MaxValue, null);
                if(roles.ResultNumber==ResultEnum.Success)
                {
                    cmbRole.DataSource = roles.Obj == null ? null : roles.Obj.Records;
                    cmbRole.DisplayMember = "Rolename";
                    cmbRole.ValueMember = "Roleid";
                }

                ResultInfo<PagingDataSet<Privilege>> pris = _sysPrivilege.GetPrivileges(1, int.MaxValue, null);
                if(pris.ResultNumber==ResultEnum.Success)
                {
                    cmbPri.DataSource = pris.Obj == null ? null : pris.Obj.Records;
                    cmbPri.DisplayMember = "Privilegename";
                    cmbPri.ValueMember = "Privilegeid";
                }

                ResultInfo<Dictionary<string, string>> res = _sysPrivilege.GetAllKeyResources();
                if(res.ResultNumber==ResultEnum.Success)
                {
                    //借用area
                    List<jsh_Area> areas=new List<jsh_Area>();
                    foreach (KeyValuePair<string, string> keyValuePair in res.Obj)
                    {
                        areas.Add(new jsh_Area(){Hot = keyValuePair.Key,Area = keyValuePair.Value});
                    }
                    cmbRes.DataSource = areas;
                    cmbRes.DisplayMember = "Area";
                    cmbRes.ValueMember = "Hot";
                }
            }
            catch (Exception e)
            {
                errorMessage += e.Message;
            }
            if(!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        #region 用户
        /// <summary>
        /// 用户管理
        /// </summary>
        private void RefreshUserManage()
        {
            string errorMessage = string.Empty;
            try
            {
                ResultInfo<PagingDataSet<UserView>> users = _sysUser.GetMulUsers(xpbUser.PageIndex,xpbUser.PageSize,txtUserName.Text,Converts.ConvertToInt(cmbRole.SelectedValue==null?"":cmbRole.SelectedValue.ToString()),Converts.ConvertToInt(cmbPri.SelectedValue==null?"":cmbPri.SelectedValue.ToString()),cmbRes.SelectedValue==null?"":cmbRes.SelectedValue.ToString());
                //_sysUser.GetUsers(xpbUser.PageIndex, xpbUser.PageSize, txtUserName.Text);
                if (users.ResultNumber == ResultEnum.Success)
                {
                    xpbUser.PageIndex = users.Obj.PageIndex;
                    xpbUser.PageSize = users.Obj.PageSize;
                    xpbUser.TotalRecordCount = users.Obj.TotalRecords;
                    xpbUser.Bind();

                    dgvUser.DataSource = users.Obj.Records;
                }
                else
                {
                    errorMessage = errorMessage + users.Describe;
                    MyMessageBox.ShowMessageBoxError(errorMessage);
                }
            }
            catch (Exception e)
            {
                errorMessage = errorMessage + e.Message;
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }


        private void cmbRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                int roleid = Converts.ConvertToInt(cmbRole.SelectedValue.ToString());
                //if(roleid>0)
                //{
                    ResultInfo<PagingDataSet<RolePrivilege>> pris = _sysRole.GetRolePrivileges(1, int.MaxValue, roleid);
                    if(pris.ResultNumber==ResultEnum.Success)
                    {
                        cmbPri.DataSource = pris.Obj == null ? null : pris.Obj.Records;
                        cmbPri.DisplayMember = "Privilegename";
                        cmbPri.ValueMember = "Privilegeid";
                    }else
                    {
                        errorMessage += pris.Describe;
                    }
                //}else
                //{
                //    errorMessage += "选取的角色不存在";
                //}
            }
            catch (Exception e1)
            {
                errorMessage += e1.Message;
            }
            if(!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        private void cmbPri_SelectedIndexChanged(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                int privid = Converts.ConvertToInt(cmbPri.SelectedValue.ToString());
                //if (privid > 0)
                //{
                    ResultInfo<Dictionary<string, string>> res = _sysPrivilege.GetPriviKeyResources(privid);
                    if (res.ResultNumber == ResultEnum.Success)
                    {
                        //借用area
                        List<jsh_Area> areas = new List<jsh_Area>();
                        foreach (KeyValuePair<string, string> keyValuePair in res.Obj)
                        {
                            areas.Add(new jsh_Area() { Hot = keyValuePair.Key, Area = keyValuePair.Value });
                        }
                        cmbRes.DataSource = areas;
                        cmbRes.DisplayMember = "Area";
                        cmbRes.ValueMember = "Hot";
                    }
                //}
                //else
                //{
                //    errorMessage += "选取的权限不存在";
                //}
            }
            catch (Exception e1)
            {
                errorMessage += e1.Message;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }


        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCheck_Click(object sender, EventArgs e)
        {
            RefreshUserManage();
        }

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            var user = new EditSUser { Text = Resources.Tips_AddUser, StartPosition = FormStartPosition.CenterParent };
            user.ShowDialog();
            if (user.DialogResult == DialogResult.OK)
            {
                txtUserName.Clear();
                RefreshUserManage();
                user.Close();
                user.Dispose();
            }
        }

        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnModify_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                int id = Convert.ToInt32(dgvUser.SelectedRows[0].Cells["userid"].Value);
                var user = new EditSUser(id)
                {
                    Text = Resources.FrmPrivilegeManage_btnRoleModify_Click_ModifyUser,
                    StartPosition = FormStartPosition.CenterParent
                };
                user.ShowDialog();
                if (user.DialogResult == DialogResult.OK)
                {
                    txtUserName.Clear();
                    RefreshUserManage();
                    user.Close();
                    user.Dispose();
                }
            }
            catch (Exception)
            {
                errorMessage = "请先选择一条记录再操作";
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                int userId = Convert.ToInt32(dgvUser.SelectedRows[0].Cells["userid"].Value);
                if (MyMessageBox.ShowMessageBoxQuestion(Resources.Tips_DeleteUser) == DialogResult.Yes)
                {
                    ResultInfo<bool> resultInfo = _sysUser.DeleteUser(userId);
                    if (resultInfo.ResultNumber == ResultEnum.Success && resultInfo.Obj)
                    {
                        errorMessage = "操作成功";
                        RefreshUserManage();
                    }
                    else
                    {
                        errorMessage = resultInfo.Describe;
                    }
                }
            }
            catch (Exception)
            {
                errorMessage = errorMessage + "请先选择一条记录再操作";
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }


        /// <summary>
        /// 用户权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX1_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                var id = Convert.ToInt32(dgvUser.SelectedRows[0].Cells["userid"].Value);
                var userRole = new EditUserRole(id)
                {
                    Text = Resources.Tips_UserRole,
                    StartPosition = FormStartPosition.CenterParent
                };
                userRole.ShowDialog();
                if (userRole.DialogResult == DialogResult.Cancel)
                {
                    txtUserName.Clear();
                    RefreshUserManage();
                    userRole.Dispose();
                }
            }
            catch (Exception)
            {
                errorMessage = "请先选择一行数据";
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        #endregion

        #region 角色
        /// <summary>
        /// 角色管理
        /// </summary>
        private void RefreshRoleManage()
        {
            string errorMessage = string.Empty;
            try
            {
                ResultInfo<PagingDataSet<Role>> roles = _sysRole.GetRoles(xpbRole.PageIndex, xpbRole.PageSize, txtRoleName.Text);
                if (roles.ResultNumber == ResultEnum.Success)
                {
                    xpbRole.PageIndex = roles.Obj.PageIndex;
                    xpbRole.PageSize = roles.Obj.PageSize;
                    xpbRole.TotalRecordCount = roles.Obj.TotalRecords;
                    xpbRole.Bind();

                    try
                    {
                        int serial = 0;
                        var roleList = new List<RoleView>();
                        foreach (Role role in roles.Obj.Records)
                        {
                            serial++;

                            var pris = new StringBuilder();
                            var rolePris = _sysRole.GetRolePrivileges(1, int.MaxValue, role.Roleid);
                            for (int i = 0; i < rolePris.Obj.TotalRecords; i++)
                            {
                                pris.Append(rolePris.Obj.Records[i].Privilegename);
                                pris.Append(",");
                            }

                            if (pris.Length <= 0)
                            {
                                pris.Append(string.Empty);
                            }

                            roleList.Add(new RoleView
                            {
                                Serial = serial,
                                RoleName = role.Rolename,
                                CreateTime = role.createtime.ToString("yyyy-MM-dd HH:mm:ss"),
                                ID = role.Roleid,
                                Pris = pris.ToString()
                            });
                        }
                        dgvRole.DataSource = roleList;

                    }
                    catch (Exception)
                    {

                        dgvRole.DataSource = roles.Obj.Records;
                    }
                }
                else
                {
                    errorMessage = errorMessage + roles.Describe;
                }
            }
            catch (Exception e)
            {
                errorMessage = errorMessage + e.Message;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        private void btnRoleAdd_Click(object sender, EventArgs e)
        {
            var sRole = new EditSRole
            {
                Text = Resources.Tips_AddRole,
                StartPosition = FormStartPosition.CenterParent
            };
            sRole.ShowDialog();
            if (sRole.DialogResult == DialogResult.OK)
            {
                txtRoleName.Clear();
                RefreshRoleManage();
                sRole.Close();
                sRole.Dispose();
            }
        }

        private void btnRoleDelete_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                int roleId = Convert.ToInt32(dgvRole.SelectedRows[0].Cells["id"].Value);
                if (MyMessageBox.ShowMessageBoxQuestion(Resources.Tips_DeleteRole) == DialogResult.Yes)
                {
                    ResultInfo<bool> resultInfo = _sysRole.DeleteRole(roleId);
                    if (resultInfo.ResultNumber == ResultEnum.Success && resultInfo.Obj)
                    {
                        errorMessage = Resources.Imformation_DoSuccess;
                        RefreshRoleManage();
                    }
                    else
                    {
                        errorMessage = resultInfo.Describe;
                    }
                }
            }
            catch (Exception)
            {
                errorMessage = errorMessage + "请先选择一条记录再操作";
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        private void btnRoleModify_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                int id = Convert.ToInt32(dgvRole.SelectedRows[0].Cells["id"].Value);
                var r = new EditSRole(id)
                {
                    Text = Resources.FrmPrivilegeManage_btnRoleModify_Click_ModifyUser,
                    StartPosition = FormStartPosition.CenterParent
                };
                r.ShowDialog();
                if (r.DialogResult == DialogResult.OK)
                {
                    txtUserName.Clear();
                    RefreshRoleManage();
                    r.Close();
                    r.Dispose();
                }

            }
            catch (Exception)
            {
                errorMessage = "请先选择一条记录再操作";
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        /// <summary>
        /// 查询角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRoleCheck_Click(object sender, EventArgs e)
        {
            RefreshRoleManage();
        }

        private void btnRolePri_Click(object sender, EventArgs e)
        {
            try
            {
                var id = Convert.ToInt32(dgvRole.SelectedRows[0].Cells["id"].Value);
                var rolePrivilege = new EidtRolePrivilege(id)
                {
                    Text = "角色权限",
                    StartPosition = FormStartPosition.CenterParent
                };
                rolePrivilege.ShowDialog();
                if (rolePrivilege.DialogResult == DialogResult.Cancel)
                {
                    txtRoleName.Clear();
                    RefreshRoleManage();
                    rolePrivilege.Dispose();
                }
            }
            catch (Exception)
            {
                MyMessageBox.ShowMessageBoxInfo("请先选择一条记录");
            }
        }

        #endregion

        #region 权限
        /// <summary>
        /// 权限管理
        /// </summary>
        private void RefreshPrivilegeManage()
        {
            string errorMessage = string.Empty;
            try
            {
                ResultInfo<PagingDataSet<Privilege>> privileges = _sysPrivilege.GetPrivileges(xpbPrivilege.PageIndex, xpbPrivilege.PageSize, txtPrivilegeName.Text);
                if (privileges.ResultNumber == ResultEnum.Success)
                {
                    xpbPrivilege.PageIndex = privileges.Obj.PageIndex;
                    xpbPrivilege.PageSize = privileges.Obj.PageSize;
                    xpbPrivilege.TotalRecordCount = privileges.Obj.TotalRecords;
                    xpbPrivilege.Bind();

                    try
                    {
                        int serial = 0;
                        var priList = new List<PrivilegeView>();
                        foreach (var privilege in privileges.Obj.Records)
                        {
                            serial++;
                            priList.Add(new PrivilegeView
                            {
                                Serial = serial,
                                PrivilegeName = privilege.Privilegename,
                                ResourceName = privilege.Privilegeresource,
                                CreateTime = privilege.createtime.ToString("yyyy-MM-dd HH:mm:ss"),
                                ID = privilege.Privilegeid
                            });
                        }
                        dgvPrivilege.DataSource = priList;

                    }
                    catch (Exception)
                    {

                        dgvPrivilege.DataSource = privileges.Obj.Records;
                    }
                }
                else
                {
                    errorMessage = errorMessage + privileges.Describe;
                }
            }
            catch (Exception e)
            {
                errorMessage = errorMessage + e.Message;
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }

        }

        /// <summary>
        /// 查询权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPCheck_Click(object sender, EventArgs e)
        {
            RefreshPrivilegeManage();
        }

        private void btnPAdd_Click(object sender, EventArgs e)
        {
            var p = new EditSPrivilege
            {
                Text = Resources.Tips_AddPri,
                StartPosition = FormStartPosition.CenterParent
            };
            p.ShowDialog();
            if (p.DialogResult == DialogResult.OK)
            {
                txtRoleName.Clear();
                RefreshPrivilegeManage();
                p.Close();
                p.Dispose();
            }
        }

        private void btnPModify_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                int id = Convert.ToInt32(dgvPrivilege.SelectedRows[0].Cells["pid"].Value);
                var r = new EditSPrivilege(id)
                {
                    Text = Resources.Tips_ModifyPri,
                    StartPosition = FormStartPosition.CenterParent
                };
                r.ShowDialog();
                if (r.DialogResult == DialogResult.OK)
                {
                    txtPrivilegeName.Clear();
                    RefreshPrivilegeManage();
                    r.Close();
                    r.Dispose();
                }

            }
            catch (Exception)
            {
                errorMessage = "请先选择一条记录再操作";
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        private void btnPDelete_Click(object sender, EventArgs e)
        {
            string errorMessage = string.Empty;
            try
            {
                int roleId = Convert.ToInt32(dgvPrivilege.SelectedRows[0].Cells["pid"].Value);
                var role = _sysPrivilege.GetPrivilege(roleId);
                if (MyMessageBox.ShowMessageBoxQuestion("是否删除权限" + role.Obj.Privilegename + "？") == DialogResult.Yes)
                {

                    ResultInfo<bool> resultInfo = _sysPrivilege.DeletePrivilege(roleId);
                    if (resultInfo.ResultNumber == ResultEnum.Success && resultInfo.Obj)
                    {
                        errorMessage = Resources.Imformation_DoSuccess;
                        RefreshPrivilegeManage();
                    }
                    else
                    {
                        errorMessage = resultInfo.Describe;
                    }
                }
            }
            catch (Exception)
            {
                errorMessage = errorMessage + "请先选择一条记录再操作";
            }
            if (!string.IsNullOrEmpty(errorMessage))
            {
                MyMessageBox.ShowMessageBoxError(errorMessage);
            }
        }

        private void btnPR_Click(object sender, EventArgs e)
        {
            try
            {
                var id = Convert.ToInt32(dgvPrivilege.SelectedRows[0].Cells["pid"].Value);
                var pr = new EditPR(id)
                {
                    Text = "权限资源",
                    StartPosition = FormStartPosition.CenterParent
                };
                pr.ShowDialog();
                if (pr.DialogResult == DialogResult.Cancel)
                {
                    txtPrivilegeName.Clear();
                    RefreshPrivilegeManage();
                    pr.Dispose();
                }
            }
            catch (Exception)
            {
                MyMessageBox.ShowMessageBoxInfo("请先选择一条记录");
            }
        }

        #endregion

        #region 资源对应的用户


        #endregion
    }
}
